<template>
  <select class="client-properties" v-model="sourceValue" value="sourceValue">
    <option v-for="option in options" :value="option.key" :class="{'selected' : option.key === sourceValue }">{{ option.value }}</option>
  </select>
</template>

<script>
  import store from '../store'
  import {showDialog, hideDialog} from '../lib/dialog'
  import {cleanClient} from '../lib/client'

  export default {
    props: {
      client: {
        require: true
      }
    },
    data() {
      return {
        options : [],
        sourceValue: ''
      }
    },
    components: {
    },
    watch: {
      sourceValue(value) {
        console.debug('custom_property:sourceValue', value, this.client.custom_property)

        if(value === 'default' || !value  || value === this.client.custom_property) return true

        let client = this.client

        if(this.alterId) clearTimeout(this.alterId)

        this.$vux.loading.show({
          text: '请稍等...'
        })

        this.alterId = setTimeout(() => {
          client.custom_property = value
          let data = cleanClient(client, this.loginUser)
          store.dispatch('saveClientInfo', data)
            .then((reseponse) => {
              this.$vux.loading.hide()
              if(reseponse.data.errcode === 0) {
                this.client.custom_property = value
                showDialog(reseponse.data.errmsg)
              } else {
                showDialog('后台发生了点小问题，请联系管理员!')
              }
              setTimeout(() => {
                hideDialog()
              }, 1500)
            })
        }, 300)
      },

      client () {
        let sourceValue = 'default'

        if(this.client.custom_property) {
          sourceValue = this.client.custom_property
        }
        this.sourceValue = sourceValue
      }
    },
    methods: {

    },
    computed: {
      customPropertyOptions () {
        return this.$store.state.app.customPropertyOptions
      },
      loginUser () {
        return this.$store.state.app.user
      }
    },
    mounted () {
      console.debug('custom_property this.client.custom_property mounted', this.client.custom_property)
      this.options = [{key:'default', value:'请选择客户属性'}].concat(this.customPropertyOptions)
      // showDialog(store, '后台发生了点小问题，请联系管理员!')
    }

  }
</script>

<style lang="less">
  .client-properties {
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top:0;
    display: inline-block;
    opacity: 0;
  }

</style>
